<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"
          ><i class="el-icon-arrow-left" />返回</span
        >
        <span>|</span>
        <span>{{ id ? '编辑企业' : '添加企业' }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            :model="addForm"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select clearable v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <!-- 
            知识点：elm ui 表单校验的字段可以很灵活的定义，比如businessLicenseId可以是其他
            任何vue的对象data里面的值，只要写的格式正确就能生效
             -->
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- 
                文件上传 
               知识点：el-upload 组件中的action属性为上传地址，一般不用它，但是它不能不写
               可以给一个值#， 一般上传都是用http-request属性进行自定义上传
              
               知识点：使用elm ui的时候，如果要实现这个效果：
               1.第一次上传一个文件
               2.第二次上传文件自动覆盖旧文件（不删除已有文件的情况下）
               可以设置:limit="2"，注意不能设置为1，如果为1，触发不了on-change事件
               -->
              <el-upload
                ref="upload"
                :http-request="uploadPic"
                action="#"
                :limit="2"
                :file-list="fileList"
                :show-file-list="true"
                :on-change="handleFileChange"
                :before-upload="handleBeforeLoad"
                :before-remove="handleBeforeRemove"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip">
                  支持扩展名：.png .jpg .jpeg，文件大小不得超过5M
                </div>
              </el-upload>
              <div class="imageContainer" v-if="addForm.businessLicenseUrl">
                <img class="license" :src="addForm.businessLicenseUrl" alt="" />
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="addEnterprise">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {
  getEnterpriseIndustryAPI,
  addEnterpriseAPI,
  getEnterpriseDetailAPI,
  editEnterpriseDetailAPI
} from '@/api/enterprise'
import { uploadAPI } from '@/api/common'
export default {
  name: 'AddEnterprise',
  data () {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      industryList: [],
      fileList: [],
      rules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        legalPerson: [
          { required: true, message: '请输入法人名称', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请输入所在行业', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '请输入联系人名字', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系电话号码', trigger: 'blur' }
        ],
        businessLicenseId: [
          {
            required: true,
            message: '请上传营业执照',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  methods: {
    //提交表单请求
    async addEnterprise () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.id) {
            await editEnterpriseDetailAPI(this.addForm)
            this.$message.success('编辑企业成功')
          } else {
            // 知识点：await只会接收状态为success的promise对象。其他状态的不会处理，此时就不会往下执行了
            await addEnterpriseAPI(this.addForm)
            this.$message.success('添加企业成功')
          }
          this.$router.go(-1)
        }
      })
    },
    handleBeforeRemove (file, fileList) {
      // 删除文件，同步修改数据
      this.addForm.businessLicenseUrl = ''
      this.addForm.businessLicenseId = ''
      this.fileList = []

      //单独校验一次
      this.$refs.ruleForm.validateField('businessLicenseId')
    },
    handleBeforeLoad (file) {
      const imageType = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      if (!imageType.includes(file.type)) {
        this.$message.warning('文件格式不正确')
        return false
      }
      if (file.size / 1024 / 1024 > 5) {
        this.$message.warning('文件大小不能超过5M')
        return false
      }
    },
    handleFileChange (file, fileList) {
      // 只保留最后选择的文件（覆盖效果）
      this.fileList = [file]
    },
    async uploadPic (upload) {
      const formData = new FormData()
      formData.append('file', upload.file)
      formData.append('type', 1)
      const { data } = await uploadAPI(formData)
      // console.log(data)
      this.addForm.businessLicenseUrl = data.url
      this.addForm.businessLicenseId = data.id
      this.$message.success('上传成功')

      //知识点：elmUI里面上传组件需要单独校验，统一校验处理不了它的状态
      this.$refs.ruleForm.validateField('businessLicenseId')
    }
  },
  async created () {
    const { data } = await getEnterpriseIndustryAPI()
    this.industryList = data

    if (this.id) {
      //回显数据
      const { data } = await getEnterpriseDetailAPI(this.id)
      // console.log(data)
      //回显图片
      this.fileList.push({
        name: data.businessLicenseName,
        url: data.businessLicenseUrl
      })

      delete data.businessLicenseName
      delete data.industryName
      delete data.rent
      this.addForm = data
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      height: 520px;
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .el-form-item__content .imageContainer {
      width: 100px;
      height: 100px;

      .license {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
